<?php

session_start();

header('Access-Control-Allow-Origin:*');

date_default_timezone_set("PRC");

header("Content-Type: text/html;charset=utf8");

require_once '../common/in_mysql.php';
require_once '../db/resource.db.php';

require_once __DIR__ . DIRECTORY_SEPARATOR . ".." . DIRECTORY_SEPARATOR . "dist" . DIRECTORY_SEPARATOR . "oss" . DIRECTORY_SEPARATOR . "samples" . DIRECTORY_SEPARATOR . "Common.php";

use OSS\OssClient;
use OSS\Core\OssException;

$action = filter_input(INPUT_POST, "action") ? filter_input(INPUT_POST, "action") : filter_input(INPUT_GET, "action");

$res = array();
switch ($action) {
    case 'listResource':
        $res = listResource();
        break;
    case 'scanResource':
        $res = scanResource();
        break;
    default :
}
echo json_encode($res);

function listResource() {
    $cs = filter_input(INPUT_POST, "Cs");
    $page = filter_input(INPUT_POST, "page");
    $pageSize = filter_input(INPUT_POST, "limit");

    if ($cs == "" || (!is_numeric($cs))) {
        $cs = -1;
    }

    if ($page == "" || (!is_numeric($page))) {
        $page = 0;
    } else if ($page > 0) {
        $page--;
    }
    if ($pageSize == "" || (!is_numeric($pageSize))) {
        $pageSize = 100;
    }

    $resourceDb = new ResourceDb();
    $data = $resourceDb->listResource($cs, $page, $pageSize);
    $array = $data['data'];
    for ($i = 0; $i < count($array); $i++) {
        $array[$i]['vol'] = $array[$i]['cs'];
        unset($array[$i]['cs']);
    }

    $res['code'] = 0;
    $res['msg'] = "";
    $res['data'] = $array;
    $res['count'] = $data['count'];
    return $res;
}

function scanResource() {
    $cs = filter_input(INPUT_POST, "Cs");
    $type = filter_input(INPUT_POST, "type");
    $ossClient = Common::getOssClient();
    $bucket = Common::getBucketName();

    switch ($type) {
        case "p":
            $dir = "res";
            break;
        case "m":
            $dir = "resm";
            break;
        default :
            $dir = "";
            break;
    }
    if ($dir == "") {
        $res['code'] = 122;
        $res['msg'] = "type类型不正确";
        return $res;
    }

    $resourceDb = new ResourceDb();
    return $resourceDb->getObjectMeta($ossClient, $bucket, $dir, $cs);
}
